package yh.thread.threadpoolcreate;

import com.alibaba.fastjson2.util.DateUtils;
import org.junit.Test;

import java.text.SimpleDateFormat;
import java.util.concurrent.*;

/**
 * 线程池执行流程验证 测试
 * @author: zyh
 * @date: 2024/10/31 16:04
 **/
public class ThreadPoolExecProcess {



    public String dateChange(Long time){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
        String format = simpleDateFormat.format(time);
        return format;
    }


    @Test
    public void ThreadPoolExecCheck() throws Exception {
        //1.创建线程池
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                1,
                2,
                60,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue(1),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.CallerRunsPolicy());

        CountDownLatch countDownLatch = new CountDownLatch(1);
        //模拟 4 个任务 在线程池中执行
        for (int i = 1; i <= 4; i++) {
            System.out.println(dateChange(System.currentTimeMillis()) + "用户开始提交任务" + i);
            Thread.sleep(1 * 1000);
           final String task = "任务" + i;
            threadPoolExecutor.execute(()->{
                try {
                    System.out.println(dateChange(System.currentTimeMillis()) + "当前线程名称：" + Thread.currentThread().getName() +"开始执行" + task );
                    Thread.sleep(10 * 1000);
                } catch (InterruptedException e) {
                    System.out.println("异常发生" + e.getMessage());
                }
                System.out.println(dateChange(System.currentTimeMillis()) + "当前线程名称：" + Thread.currentThread().getName() + "执行任务完成" );
            });
        }
        //阻塞主线程，观察任务执行过程，否则看不到 任务从 提交->执行->完成 的状态变化
        countDownLatch.await();
    }
}
